package com.dogkr.server.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dogkr.server.entity.Host;
import com.dogkr.server.entity.HostApply;
import com.dogkr.server.entity.UserMessage;
import com.dogkr.server.entity.UserMessage.Answer;
import com.dogkr.server.entity.UserMessage.Read;
import com.dogkr.server.mapper.HostApplyMapper;
import com.dogkr.server.mapper.HostMapper;
import com.dogkr.server.mapper.UserMessageMapper;
import com.sean.common.page.Pagination;
import com.sean.common.page.ResultPagination;
import com.sean.common.service.BaseService;
import com.sean.common.utils.StringUtils;


@Service
public class MessageService extends BaseService {

	@Autowired
	private UserMessageMapper userMessageMapper;

	/**
	 * 将信息标志为已读.
	 * @param orerId
	 */
	public int updateReadByOrderKey(Long orerId) {
		UserMessage record = new UserMessage();
		record.setOrderId(orerId);
		record.setIsRead(Read.READ);
		return userMessageMapper.updateByOrderKeySelective(record);
	}
	/**
	 * 将信息标志为已处理.
	 * @param orerId
	 */
	public int updateAnswerByOrderKey(Long orerId) {
		UserMessage record = new UserMessage();
		record.setOrderId(orerId);
		record.setIsAnswer(Answer.ANSWER);
		return userMessageMapper.updateByOrderKeySelective(record);
	}
	
	public UserMessage selectMessageById(Long userId, Long msgId) {
		UserMessage msg = userMessageMapper.selectByPrimaryKey(msgId);
		if(msg.getUserId().longValue() == userId.longValue()) {
			if(msg.getIsRead() == UserMessage.Read.UNREAD.getVal()) {
				UserMessage updateMsg = new UserMessage();
				updateMsg.setId(msgId);
				updateMsg.setRead();
				userMessageMapper.updateByPrimaryKeySelective(updateMsg);
			}
			return msg;
		}
		return null;
	}

	public void insertMessage(UserMessage msg, Long askId) {
		msg.setIsRead(UserMessage.Read.UNREAD);
		msg.setCreateDate(new Date());
		userMessageMapper.insert(msg);
		if(askId != null) {
			UserMessage ask = userMessageMapper.selectByPrimaryKey(askId);
			if(ask != null) {
				ask.setIsAnswer(Answer.ANSWER);
				ask.setMsgAnswerId(msg.getId());
				ask.setMsgAnswerDate(new Date());
				userMessageMapper.updateByPrimaryKeySelective(ask);
			}
		}
	}
	
	public int checkUnreadMessage(Long userId) {
		return userMessageMapper.checkUnreadByUserId(userId);
	}
	
	/**
	 * 查询消息.
	 * @param userId
	 * @param pagination
	 * @return
	 */
	public ResultPagination<UserMessage> selectMessage(long userId, Pagination pagination) {
		pagination.putParam("userId", userId);
		return this.selectListForPage(UserMessageMapper.class, "selectWithList", pagination, UserMessage.class);
	}
}
